from datetime import date, timedelta, datetime
import random
from rest_framework.views import APIView
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django import forms
from order.models import Orders, Orderproduct , Orderlogistics,Returnapplication
from products.models import Products
from users.models import Users


class OrderForm(forms.Form):
    orderid = forms.CharField(label='orderid')
# Create your views here.
class order(APIView):
    def get(self,request):
        return render(request, 'order.html')
    def post(self,request):
        action = request.POST.get('action')
        if action == '1':
            productid = request.session.get('productid')
            product=Products.objects.get(productid=productid)
            username= request.session.get('username')
            user=Users.objects.get(username=username)
            userid=user.userid
            order=Orders.objects.create(
                orderid=str(random.randint(0, 9999)),
                userid=Users.objects.get(userid=userid),
                payment_method='01',  # 支付方式，假设为'01'表示某种支付方式
                order_time=date.today(),  # 订单时间，假设为今天
                transaction_time=date.today(),  # 交易时间，假设为今天
                itemcount=1,  # 商品数量
                payment_time=date.today(),  # 支付时间，假设为今天
                expected_delivery_date=date.today() + timedelta(days=1), # 预计发货日期
                total_amount=product.price,  # 总金额
                actual_payment=product.price,  # 实际支付金额
                order_status='01',  # 订单状态，假设为'01'表示某种状态
            )
            orderproduct = Orderproduct.objects.create(
                orderid=order.orderid,
                productid=product,
                number=1,
            )
            # 执行增加操作的逻辑
            return HttpResponse("创建订单成功")
        elif action == '2':
            # 执行删除操作的逻辑

            return redirect('订单已删除')
        elif action == '3':
            # 执行修改操作的逻辑
            form = OrderForm(request.POST)
            if form.is_valid():
                # 处理表单数据，例如更新数据库中的用户信息
                # orderid=form.cleaned_data['orderid']
                # order = Orders.objects.get(orderid=orderid)  # 获取当前用户
                # order.order_status = form.cleaned_data['status']
                # order.save()
                return HttpResponse("用户信息修改成功")
            else:
                messages.error(request, "表单数据有误，请检查后重新提交")
                return render(request, 'personal.html', {'form': form})
        elif action == '4':
            username=request.session.get("username")
            form = OrderForm(request.POST)
            user=Users.objects.get(username=username)
            userid=user.userid
            order = Orders.objects.filter(userid=userid)
            return_orders=[]
            # 执行查询操作的逻辑
            for iorder in order:
                status = ""
                if iorder.order_status == '01':
                    status = "正常进行"
                elif iorder.order_status == '02':
                    status = "已取消"
                elif iorder.order_status == '10':
                    status = "退货申请中"
                return_orders.append({
                    'status': status,
                    'orderid': iorder.orderid,
                    # 添加其他需要展示的字段
                })
            #return HttpResponse(return_orders)
            return render(request, 'order.html', {'order': return_orders, 'form': form})
        else:
            return HttpResponse("未知操作")

from django import forms
class ReturnForm(forms.Form):
    orderid = forms.CharField(label='订单号',required=False)
    #status = forms.CharField(label='状态')

###取消订单
class Return(APIView):
    def get(self,request):
        form = ReturnForm()
        return render(request, 'return.html', {'form': form})
    def post(self,request):
        username = request.session.get('username')
        user = Users.objects.get(username=username)
        userid = user.userid
        action = request.POST.get('action')
        if action == '3':
            form = ReturnForm(request.POST)
            if form.is_valid():
                orderid = form.cleaned_data['orderid']
                if orderid:
                    try:
                        order=Orders.objects.get(orderid=orderid)
                        order.order_status="02"
                        order.save()
                        id=random.randint(0, 99999)
                        #neworder= Orderlogistics.obejects.create(tracking_number=id,orderid=orderid,delivery_time=date.today(),)
                        return render(request, 'return.html', {'form': form,'message':messages})
                    except:
                        messages.error(request, "订单不存在")
                        return render(request, 'return.html', {'form': form,'message':messages})

                else :
                    return HttpResponse("请输入表单")
            return HttpResponse("表单提交错误")
        elif action == '2':
            return HttpResponse("执行了2操作")
        elif action == '1':
            return HttpResponse("执行了3操作")
        elif action == '4':
            orders=[]
            order= Orders.objects.filter(userid=userid)
            order=order.filter(order_status="02")
            for iorder in order:
                orders.append({
                    'status': "已取消",
                    'orderid': iorder.orderid,

                    # 添加其他需要展示的字段
                })
            form = ReturnForm(request.POST)
            return render(request, 'return.html', {'returnorders': orders, 'form': form})

class LogisticsForm(forms.Form):
    orderid = forms.CharField(label='订单号',required=False)

#####发货处理功能
class LogisticsView(APIView):
    def get(self, request):
        form = ReturnForm()
        return render(request, 'logistics.html', {})
    def post(self, request):
        action = request.POST.get('action')
        if action == '1':
            return render(request, 'logistics.html', {})
        elif action == '2':
            ####查询未处理订单
            orders=[]
            order= Orders.objects.filter(order_status='01')
            form = LogisticsForm(request.POST)
            for iorder in order:
                orders.append({
                    'status': "未发货",
                    'id': iorder.orderid,
                })
            return render(request, 'logistics.html', {'backend_message': orders, 'form': form})
        elif action == '3':
            # 执行修改操作的逻辑
            form = ReturnForm(request.POST)
            if form.is_valid():
                orderid = form.cleaned_data["orderid"]
                try:
                    order = Orders.objects.get(orderid=orderid)
                    order.order_status = "03"
                    order.save()
                    tracking_number=random.randint(1, 99999)
                    new_order = Orderlogistics.objects.create(orderid=order,
                                                              tracking_number=tracking_number,
                                                              logistics_company_id='01',
                                                              freight=6,
                                                              delivery_time=date.today(),
                                                              )
                    return HttpResponse("发货成功！")
                except:
                    return HttpResponse("订单不存在！")
            return HttpResponse("提交表单失败！")
        elif action == '4':
            ####查询所有订单
            form = LogisticsForm(request.POST)
            order = Orders.objects.all()
            backend_message = []
            for i in order:
                status=''
                tracking_number=''
                if(i.order_status=='01'):
                    status='未发货'
                elif(i.order_status=='02'):
                    status='已取消'
                elif (i.order_status == '03'):
                    status = '已发货'
                    tracking=Orderlogistics.objects.get(orderid=i.orderid)
                    tracking_number=tracking.tracking_number
                elif (i.order_status == '04'):
                    status = '已收货'
                elif (i.order_status == '10'):
                    status = '退货申请中'
                backend_message.append({
                    'id': i.orderid,
                    'status': status,
                    'tracking_number': tracking_number,
                })

            # 执行查询操作的逻辑
            return render(request, 'logistics.html', {'backend_message': backend_message, 'form': form})
        else:
            return HttpResponse("未知操作")


class RequestreturnForm(forms.Form):
    orderid = forms.CharField(label='订单号',required=False)
    returnreason = forms.CharField(label='退货原因', required=False)
    #status = forms.CharField(label='状态')

class Requestreturn(APIView):
    def get(self,request):
        form = RequestreturnForm()
        return render(request, 'requestreturn.html', {'form': form})
    def post(self,request):
        username = request.session.get('username')
        user = Users.objects.get(username=username)
        userid = user.userid
        action = request.POST.get('action')
        if action == '3':
            form = RequestreturnForm(request.POST)
            if form.is_valid():
                orderid = form.cleaned_data['orderid']
                if orderid:
                #try:
                    orders = Orders.objects.get(orderid=orderid)
                    if(orders.order_status == '02'):
                        return HttpResponse("订单已取消")
                    if (orders.order_status == '10'):
                        return HttpResponse("该订单已申请退货")
                    userid = userid
                    applytime = datetime.now()
                    returnid = random.randint(0, 9999)
                    requestreturn = Returnapplication.objects.create(returnstatus="10", orderid=orders,userid = user,applytime =applytime, returnid=returnid)
                    # requestreturn.applytime=datetime.now()
                    # requestreturn.returnid =random.randint(0,9999)
                    # requestreturn.userid=userid
                    orders.order_status ="10"
                    orders.save()
                    return HttpResponse("退货已申请")
                #except:
                    messages.error(request, "订单不存在")
                    return render(request, 'requestreturn.html', {'form': form,'message':messages})

                else :
                    return HttpResponse("请输入订单号")
            return HttpResponse("订单号提交错误")
        elif action == '2':
            return HttpResponse("执行了2操作")
        elif action == '1':
            return HttpResponse("执行了3操作")
        elif action == '4':
            requestreturns=[]
            order= Returnapplication.objects.filter()
            for iorder in order:
                status=""
                if iorder.returnstatus == "10":
                    status= "待商家处理"
                elif iorder.returnstatus == "20":
                    status= "已退货成功"
                requestreturns.append({
                    'status':status,
                    'orderid': iorder.orderid,
                    'returnid':iorder.returnid,
                    'time':iorder.applytime
                    # 添加其他需要展示的字段
                })
            form = RequestreturnForm(request.POST)
            return render(request, 'requestreturn.html', {'requestreturns': requestreturns, 'form': form})


class order(APIView):
    def get(self,request):
        return render(request, 'order.html')
    def post(self,request):
        action = request.POST.get('action')
        if action == '1':
            productid = request.session.get('productid')
            product=Products.objects.get(productid=productid)
            username= request.session.get('username')
            user=Users.objects.get(username=username)
            userid=user.userid
            order=Orders.objects.create(
                orderid=str(random.randint(0, 9999)),
                userid=Users.objects.get(userid=userid),
                payment_method='01',  # 支付方式，假设为'01'表示某种支付方式
                order_time=date.today(),  # 订单时间，假设为今天
                transaction_time=date.today(),  # 交易时间，假设为今天
                itemcount=1,  # 商品数量
                payment_time=date.today(),  # 支付时间，假设为今天
                expected_delivery_date=date.today() + timedelta(days=1), # 预计发货日期
                total_amount=product.price,  # 总金额
                actual_payment=product.price,  # 实际支付金额
                order_status='01',  # 订单状态，假设为'01'表示某种状态
            )
            orderproduct = Orderproduct.objects.create(
                orderid=order.orderid,
                productid=product,
                number=1,
            )
            # 执行增加操作的逻辑
            return HttpResponse("创建订单成功")
        elif action == '2':
            # 执行删除操作的逻辑

            return redirect('订单已删除')
        elif action == '3':
            # 执行修改操作的逻辑
            form = OrderForm(request.POST)
            if form.is_valid():
                # 处理表单数据，例如更新数据库中的用户信息
                # orderid=form.cleaned_data['orderid']
                # order = Orders.objects.get(orderid=orderid)  # 获取当前用户
                # order.order_status = form.cleaned_data['status']
                # order.save()
                return HttpResponse("用户信息修改成功")
            else:
                messages.error(request, "表单数据有误，请检查后重新提交")
                return render(request, 'personal.html', {'form': form})
        elif action == '4':
            username=request.session.get("username")
            form = OrderForm(request.POST)
            user=Users.objects.get(username=username)
            userid=user.userid
            order = Orders.objects.filter(userid=userid)
            return_orders=[]
            # 执行查询操作的逻辑
            for iorder in order:
                status = ""
                if iorder.order_status == '01':
                    status = "正常进行"
                elif iorder.order_status == '02':
                    status = "已取消"
                elif iorder.order_status == '10':
                    status = "退货申请中"
                return_orders.append({
                    'status': status,
                    'orderid': iorder.orderid,
                    # 添加其他需要展示的字段
                })
            #return HttpResponse(return_orders)
            return render(request, 'order.html', {'order': return_orders, 'form': form})
        else:
            return HttpResponse("未知操作")


'''
class Orderlogistics(models.Model):
    tracking_number = models.CharField(db_column='tracking_number', primary_key=True,
                                       max_length=5)  # Field name made lowercase.
    orderid = models.ForeignKey(Orders, models.DO_NOTHING, db_column='orderid', blank=True,
                                null=True)  # Field name made lowercase.
    logistics_company_id = models.CharField(db_column='logistics_company_id', max_length=5, blank=True,
                                            null=True)  # Field name made lowercase.
    freight = models.FloatField(db_column='freight', blank=True, null=True)  # Field name made lowercase.
    delivery_time = models.DateField(db_column='delivery_time', blank=True, null=True)  # Field name made lowercase.
    receipt_time = models.DateField(db_column='receipt_time', blank=True, null=True)  # Field name made lowercase.
'''



class wuliuForm(forms.Form):
    orderid = forms.CharField(label='订单号',required=True)
    tracking_number= forms.CharField(label='物流单号', required=True)


class wuliu(APIView):
    def get(self,request):
        form = wuliuForm()
        return render(request, 'wuliu.html', {'form': form})
    def post(self,request):
        action = request.POST.get('action')
        #####查询所有物流订单
        if action == '1':
            form = wuliuForm()
            order=[]
            wulius=Orderlogistics.objects.filter()
            for iwulius in wulius:
                order.append({
                    'tracking_number':iwulius.tracking_number,
                    'orderid':iwulius.orderid,
                    'logistics_company_id':iwulius.logistics_company_id,
                    'freight':iwulius.freight,
                    'delivery_time':iwulius.delivery_time,
                    'receipt_time':iwulius.receipt_time,})
            return render(request, 'wuliu.html',
                          {'order': wulius, 'form': form,'message':messages})
        elif action == '4':
            form = wuliuForm(request.POST)
            if form.is_valid():
                orderid = form.cleaned_data.get('orderid')
                tracking_number = form.cleaned_data.get('tracking_number')
                try:
                    order = Orders.objects.get(orderid=orderid)
                    wuliu = Orderlogistics.objects.create(orderid=order, tracking_number=tracking_number)
                    return HttpResponse("成功录入物流信息")
                except:
                    return HttpResponse("订单信息不存在")
            else:
                return HttpResponse("操作失误")

#####没写完

'''
class Orderlogistics(models.Model):
    tracking_number = models.CharField(db_column='tracking_number', primary_key=True,
                                       max_length=5)  # Field name made lowercase.
    orderid = models.ForeignKey(Orders, models.DO_NOTHING, db_column='orderid', blank=True,
                                null=True)  # Field name made lowercase.
    logistics_company_id = models.CharField(db_column='logistics_company_id', max_length=5, blank=True,
                                            null=True)  # Field name made lowercase.
    freight = models.FloatField(db_column='freight', blank=True, null=True)  # Field name made lowercase.
    delivery_time = models.DateField(db_column='delivery_time', blank=True, null=True)  # Field name made lowercase.
    receipt_time = models.DateField(db_column='receipt_time', blank=True, null=True)  # Field name made lowercase.


'''